﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;
using System.Globalization;

namespace JM.JCY.SharePointComponent.PhotoAlbum.AddMoreMedia
{
    public partial class AddMoreMediaUserControl : UserControl
    {
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        public string _SPfolderID
        {
            get;
            set;
        }

        public string _albumId
        {
            get;
            set;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                LoadApplicationContext();

                string CreateAlbum = Request.Params.Get("__EVENTTARGET");
                if (CreateAlbum != null && CreateAlbum.IndexOf("addmore") > -1)
                {
                    ImgBtnSave_Click(null, null);
                }
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("addmore loading", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }
        }

        private void LoadApplicationContext()
        {
            if (Request.Params["albumId"] != null)
            {
                _staffId = 11;
                if (ApplicationContext.Current.GetKeyValue("userId") != null)
                {
                    _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
                }

                if (ApplicationContext.Current.GetKeyValue("appType") != null)
                {
                    appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
                }

                switch (appType)
                {
                    case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                        appId = 0;
                        break;
                    case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                        appId = _staffId;
                        break;
                    case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                        if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                        {
                            appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                        }
                        break;
                    case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                        if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                        {
                            appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                        }
                        break;
                }

                _albumId = Request.Params["albumId"];

                using (PhotoAlbumProxy accessProxy = new PhotoAlbumProxy())
                {
                    PhotoAlbumDataSet albumds = accessProxy.getAlbumDbyAlbumId(Convert.ToInt32(_albumId));
                    if (albumds.T_SharePointObject.Rows.Count > 0)
                    {
                        _SPfolderID = albumds.T_SharePointObject.Rows[0][albumds.T_SharePointObject.SPFolderIdColumn.ColumnName].ToString();
                    }
                }
            }
        }

        public DataTable sessionKeys
        {
            get
            {
                DataTable dt = new DataTable();
                DataColumn dc = new DataColumn();
                dc.ColumnName = "fileType";
                dt.Columns.Add(dc);

                DataColumn dc2 = new DataColumn();
                dc2.ColumnName = "fileKey";
                dt.Columns.Add(dc2);

                DataColumn dc3 = new DataColumn();
                dc3.ColumnName = "fileTypeName";
                dt.Columns.Add(dc3);

                DataColumn dc4 = new DataColumn();
                dc4.ColumnName = "filePath";
                dt.Columns.Add(dc4);

                DataColumn dc5 = new DataColumn();
                dc5.ColumnName = "orgFileName";
                dt.Columns.Add(dc5);

                return dt;
            }
        }

        protected void ImgBtnSave_Click(object sender, ImageClickEventArgs e)
        {
            DataTable tableKeys = getFilesDetailToDataTable();
            SPWeb CurrentWeb = SPContext.Current.Web;
            try
            {
                string siteName = string.Empty;
                switch (SPContext.Current.Web.ServerRelativeUrl.ToLower())
                {
                    case "/":
                        siteName = string.Empty;
                        break;
                    case "/mysite":
                        siteName = JCYConstant.SiteUrlName.MySite;
                        break;
                    case "/mydept":
                        siteName = JCYConstant.SiteUrlName.MyDept;
                        break;
                    case "/mycommittee":
                        siteName = JCYConstant.SiteUrlName.MyCommittee;
                        break;
                }

                using (PhotoAlbumProxy funProxy = new PhotoAlbumProxy())
                {
                    SPInputs uploadAlbumInput = new SPInputs();
                    List<byte[]> mediaList = new List<byte[]>();
                    List<string> mediaExtension = new List<string>();

                    DataTable mediaTable = new DataTable();
                    DataColumn dc1 = new DataColumn();
                    dc1.ColumnName = "FilePath";
                    mediaTable.Columns.Add(dc1);
                    DataColumn dc2 = new DataColumn();
                    dc2.ColumnName = "PicPath";
                    mediaTable.Columns.Add(dc2);

                    string picName = "";
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        picName = Guid.NewGuid().ToString().Replace("-", "");

                        DataRow mediaRow = mediaTable.NewRow();
                        if (keyRow["fileType"].ToString().Equals("pic"))
                        {
                            // pic type
                            mediaExtension.Add("." + keyRow["fileTypeName"].ToString());
                            if (Session[keyRow["fileKey"].ToString()] != null)
                            {
                                byte[] mediaStream = (byte[])Session[keyRow["fileKey"].ToString()];
                                mediaList.Add(mediaStream);
                            }
                        }
                    }
                    uploadAlbumInput.MediaStream = mediaList;
                    uploadAlbumInput.MediaExtension = mediaExtension;
                    uploadAlbumInput.MediaTable = mediaTable;
                    uploadAlbumInput.ApplicationType = appType;
                    uploadAlbumInput.SiteName = siteName;
                    uploadAlbumInput.SPFolderID = _SPfolderID;
                    uploadAlbumInput.MediaStream = mediaList;
                    uploadAlbumInput.MediaExtension = mediaExtension;
                    uploadAlbumInput.SharingOption = "All";

                    SPOutputs spout = JCYSharePointHelper.UploadMedia(uploadAlbumInput);
                    if (!spout.IsError)
                    {
                        DataTable outTable = spout.OutputsTable;
                        string picFolderID = string.Empty, mediaFolderID = string.Empty;

                        var albumDS = funProxy.getAlbumDbyAlbumId(Convert.ToInt32(_albumId));
                        PhotoAlbumDataSet.T_AlbumRow albumRow = albumDS.T_Album[0];

                        for (int i = 0; i < outTable.Rows.Count; i++)
                        {
                            DataRow outRow = outTable.Rows[i];
                            // insert sharepoint object table

                            var newObjectRow = albumDS.T_SharePointObject.NewT_SharePointObjectRow();
                            newObjectRow.SPSiteName = CurrentWeb.Title;
                            newObjectRow.SPListName = appType;
                            newObjectRow.SPFolderId = outRow["FolderID"].ToString();
                            newObjectRow.SPListItemId = outRow["ItemID"].ToString();
                            newObjectRow.IsDeleted = false;

                          JCYUtility.UpdateCommonFields(newObjectRow, "aa");
                          albumDS.T_SharePointObject.AddT_SharePointObjectRow(newObjectRow);


                            //update album table.

                            albumRow.ItemCount += 1;
                            albumRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                            albumRow.LatestUpdateTime = DateTime.Now;

                            // insert album content table  
                            var newAlbumContentRow = albumDS.T_AlbumContent.NewT_AlbumContentRow();
                            newAlbumContentRow.AlbumId = Convert.ToInt32(_albumId);
                            newAlbumContentRow.ThumbNailImgUrl = outRow["ThumbNailImgUrl"].ToString();
                            newAlbumContentRow.OriginalImgUrl = outRow["OriginalImgUrl"].ToString();
                            newAlbumContentRow.OptimizeImgUrl = outRow["OptimizeImgUrl"].ToString();
                            newAlbumContentRow.StaffId = _staffId;
                            newAlbumContentRow.Description = string.Empty;
                            newAlbumContentRow.IsDeleted = false;
                            newAlbumContentRow.SharePointObjectId = newObjectRow.SharePointObjectId;
                            JCYUtility.UpdateCommonFields(newAlbumContentRow, "A");
                            albumDS.T_AlbumContent.AddT_AlbumContentRow(newAlbumContentRow);
                        }

                        funProxy.CreateAlbumwithUpload(albumDS);

                        
                    }
                    else
                    {
                        //Error.
                        Exception ex = new Exception(spout.Message.Replace("\r\n", ""));
                        bool isok = JCYUtility.ExceptionHandle("addmore save", ex);
                        if (isok == false)
                        {
                            throw ex;
                        }
                        return;
                    }
                    //clear all session byte[].
                    foreach (DataRow keyRow in tableKeys.Rows)
                    {
                        if (Session[keyRow["fileKey"].ToString()] != null)
                        {
                            Session.Remove(keyRow["fileKey"].ToString());
                        }
                    }
                    tableKeys.Rows.Clear();
                }

                Response.Redirect("ViewAlbum.aspx?AlbumId=" + Request.Params["albumId"]);
            }
            catch (Exception ex)
            {
                bool isok = JCYUtility.ExceptionHandle("addmore save", ex);
                if (isok == false)
                {
                    throw ex;
                }
            }

        }

        public DataTable getFilesDetailToDataTable()
        {
            DataTable dt = sessionKeys;
            try
            {
                string uploadPath = System.Configuration.ConfigurationManager.AppSettings["uploadPath"].ToString();
                uploadPath = Context.Server.MapPath(uploadPath);
                if (uploadPath.EndsWith("\\") == false)
                {
                    uploadPath = uploadPath + "\\";
                }

                string logFileName = HiddenFieldGuid.Value.Replace("-", "") + ".txt";
                if (File.Exists(uploadPath + logFileName))
                {
                    string[] fileLines = File.ReadAllLines(uploadPath + logFileName);

                    foreach (string stg in fileLines)
                    {
                        string[] fileDetail = stg.Split(new char[] { '?' });
                        DataRow row = dt.NewRow();
                        //row["fileType"] = "pic";
                        //row["filePath"] = uploadPath + fileName;
                        //row["fileTypeName"] = fileTypeName;
                        //row["orgFileName"] = file.FileName;
                        if (fileDetail[0].Equals("pic"))
                        {
                            FileStream fs = new FileStream(fileDetail[1], FileMode.Open, FileAccess.Read);
                            byte[] fileBuffer = new byte[fs.Length];
                            fs.Read(fileBuffer, 0, fileBuffer.Length);
                            fs.Close();
                            fs.Dispose();

                            string fileKey = Guid.NewGuid().ToString();
                            Session[fileKey] = fileBuffer;

                            row["fileType"] = fileDetail[0];
                            row["fileKey"] = fileKey;
                            row["filePath"] = fileDetail[1];
                            row["fileTypeName"] = fileDetail[2];
                            row["orgFileName"] = fileDetail[3];

                        }
                        else if (fileDetail[0].Equals("mv"))
                        {
                            row["fileType"] = "mv";
                            row["fileKey"] = "";
                            row["fileTypeName"] = fileDetail[2];
                            row["filePath"] = fileDetail[1];
                            row["orgFileName"] = fileDetail[3];
                        }
                        else
                        {
                            row["fileType"] = fileDetail[0];
                            row["fileKey"] = "";
                            row["fileTypeName"] = fileDetail[2];
                            row["filePath"] = fileDetail[1];
                            row["orgFileName"] = fileDetail[3];
                        }
                        dt.Rows.Add(row);
                    }
                }
                else
                {
                    throw new Exception("Can not find files log detail information:" + uploadPath + logFileName);
                }
            }
            catch (Exception ex)
            {
               JCYUtility.ExceptionHandle("getFilesDetails", ex);
            }

            return dt;
        }
    }
}
